//
//  FirstViewController.m
//  Struggle
//
//  Created by Zyf on 16/7/5.
//  Copyright © 2016年 lexiao. All rights reserved.
//

#import "FirstViewController.h"
#import "SecondViewController.h"

@interface FirstViewController () <UIWebViewDelegate>
{
    NSString *_Url;
    NSArray *_lxArray;
    NSString *_shareUrl;
    NSString *_shareTitle;
    NSString *_shareCon;
    NSString *_shareImg;
    
}

@property (nonatomic, strong) UIWebView *webView;

@end

@implementation FirstViewController

- (instancetype)initWithUrlString:(NSString *)string {
    if (self = [super init]) {
        _Url = string;
    }
    return self;
}

- (UIWebView *)webView {
    if (!_webView) {
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height - 20)];
        _webView.scalesPageToFit = YES;
        _webView.delegate = self;
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_Url]];
        [self.webView loadRequest:request];
        
        NSString *ua = [_webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
        NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%@ lexiao", ua],@"UserAgent", nil];
        [[NSUserDefaults standardUserDefaults] registerDefaults:dict];
    }
    return _webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.webView];
    
    self.webView.scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshWebView)];
    
    NSLog(@"FirstViewController");
}

- (void)refreshWebView {
    [self.webView reload];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([USERDEFAULTS_GET(@"BackPage") isEqualToString:@"yes"]) {
        [self.webView reload];
        USERDEFAULTS_SET(@"no", @"BackPage");
    }
    
    if ([USERDEFAULTS_GET(@"UpdateImage") isEqualToString:@"yes"]) {
        [self.webView reload];
        
        USERDEFAULTS_SET(@"no", @"UpdateImage");
    }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *currentUrl = webView.request.URL.absoluteString;
    NSLog(@"网页加载完毕 :%@", currentUrl);
    
    [self.webView.scrollView.mj_header endRefreshing];
    
    NSString *url1 = @"http://hhr.ts.lexiao360.com/";
    NSString *url2 = @"http://hhr.ts.lexiao360.com/Login/Index";
    
    if ([currentUrl isEqualToString:url1] || [currentUrl isEqualToString:url2]) {
        return;
    }else {
        if ([currentUrl containsString:@"lx_target_self=true"]) {
            return;
        }
        
        [self addBackButton];
    }
}

- (void)addBackButton {
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 44, 44)];
    button.backgroundColor = [UIColor clearColor];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)buttonClick:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSString *currentUrl = request.URL.absoluteString;
    
    NSLog(@"请求头: %@", request.URL.scheme);
    
    NSLog(@"First请求的地址: %@", currentUrl);
    
    NSString *today1 = @"today/type/0/tr/0.html";
    NSString *today2 = @"today/type/1/tr/0.html";
    
    if ([currentUrl containsString:@"lx_target_self=true"] || [currentUrl containsString:@"upload_avatar"] || [request.URL.absoluteString containsString:@"s=/Partner/Index/my.html"] || [currentUrl containsString:today1] || [currentUrl containsString:today2] || [currentUrl containsString:@"logout.html"] || [currentUrl containsString:@"s=/Partner/Index/index.html"]) {
        if ([currentUrl containsString:@"logout.html"]) {
            USERDEFAULTS_SET(@"yes", @"OUT");
        }
        
        if ([currentUrl containsString:@"upload_avatar"]) {
            USERDEFAULTS_SET(@"yes", @"UpdateImage");
        }
        return YES;
    }else if ([currentUrl containsString:@"close_current_page"]) {
        NSLog(@"设置成功返回上级页面");
        
        USERDEFAULTS_SET(@"yes", @"BackPage");
        
        [self.navigationController popViewControllerAnimated:YES];
        
        return NO;
    }
    
    if ([currentUrl containsString:@"action=share"]) {
        _lxArray = [currentUrl componentsSeparatedByString:@"&"];
        for (int i = 0; i < _lxArray.count; i++) {
            if (i == 0) {
                continue;
            }
            
            if (i == 1) {
                NSString *temp = [_lxArray[i] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                _shareUrl = [temp substringFromIndex:9];
                NSLog(@"截取URL:  %@", _shareUrl);
            }
            
            if (i == 2) {
                NSString *temp = [_lxArray[i] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                _shareTitle = [temp substringFromIndex:11];
                NSLog(@"截取TITLE:  %@", _shareTitle);
            }
            
            if (i == 3) {
                NSString *temp = [_lxArray[i] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                _shareCon = [temp substringFromIndex:9];
                NSLog(@"截取Con:  %@", _shareCon);
            }
            
            if (i == 4) {
                NSString *temp = [_lxArray[i] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                _shareImg = [temp substringFromIndex:9];
                NSLog(@"截取IMG:  %@", _shareImg);
            }
            
        }
        
        [self UmengShare];
        
        return NO;
        
    }
    
    if ([currentUrl isEqualToString:_Url]) {
        return YES;
    }else {
        if ([@"sms" isEqualToString:request.URL.scheme] || [@"tel" isEqualToString:request.URL.scheme]) {
            return YES;
        }
        
        NSLog(@"跳转到下一个控制器!");
        SecondViewController *svc = [[SecondViewController alloc] initWithUrlString:currentUrl];
        [self.navigationController pushViewController:svc animated:YES];
        return NO;
    }
    
    return NO;
}

- (void)UmengShare {
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"577f69cce0f55abe820007ad"
                                      shareText:_shareCon
                                     shareImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_shareImg]]]
                                shareToSnsNames:@[UMShareToWechatSession, UMShareToWechatTimeline, UMShareToQQ, UMShareToQzone]
                                       delegate:self];
}

- (void)didSelectSocialPlatform:(NSString *)platformName withSocialData:(UMSocialData *)socialData {
    if (platformName == UMShareToWechatSession) {
        NSLog(@"分享到微信好友");
        socialData.extConfig.title = _shareTitle;
        socialData.extConfig.wechatSessionData.url = _shareUrl;
    }else if (platformName == UMShareToWechatTimeline){
        NSLog(@"分享到微信朋友圈");
        socialData.extConfig.title = _shareTitle;
        socialData.extConfig.wechatTimelineData.url = _shareUrl;
    }else if (platformName == UMShareToQQ) {
        NSLog(@"分享到QQ好友");
        socialData.extConfig.title = _shareTitle;
        socialData.extConfig.qqData.url = _shareUrl;
    }else if (platformName == UMShareToQzone) {
        NSLog(@"分享到QQ空间");
        socialData.extConfig.title = _shareTitle;
        socialData.extConfig.qzoneData.url = _shareUrl;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

